extends Node


signal hp_changed(new_value) # UI 更新信号
signal sheild_changed(new_value)
signal game_over(is_victory) # 游戏结束信号
signal core_get_damage(damage)
signal mouse_left()

# 游戏全局参数
var game_speed: float = 1.0 # 用于控制暂停 (0) 或加速 (2)
var max_hp: float = 100.0
var max_sheild: float = 100.0
var core_position: Vector2
var enemy_data = load_json_simple("res://JSON/enemy_data.json")
var kill_nums: int = 0

var last_damage_time: float = 0.0 # 记录上次受伤时间
const SHIELD_RECOVERY_DELAY: float = 3.0 # 护盾恢复延迟（秒）
const SHIELD_RECOVERY_RATE: float = 10.0 # 护盾恢复速率（每秒）

# 资源管理 (使用 setget 属性访问器)
var current_hp: float = 100.0:
	set(value):
		current_hp = clamp(value, 0, max_hp)
		hp_changed.emit(current_hp) # 只要数值变动，自动通知 UI

var current_sheild: float = 100.0:
	set(value):
		current_sheild = clamp(value, 0, max_sheild)
		sheild_changed.emit(current_sheild)

func _ready():
	print("Global Manager initialized.")
	core_get_damage.connect(get_damage)
	last_damage_time = Time.get_ticks_msec() / 1000.0
	
	
func _process(delta: float) -> void:
	if Input.is_action_pressed("exit"):
		get_tree().quit()
	if Input.is_action_pressed("shoot"):
		mouse_left.emit()

	# 护盾自动恢复逻辑
	auto_recover_shield()

# 增加资源
func add_hp(amount: float):
	current_hp += amount

#受伤函数
func get_damage(amount: float):
	last_damage_time = Time.get_ticks_msec() / 1000.0

	#在伤害能够被盾所承受时，首先消耗盾，破盾伤害不被血量所承担
	if current_sheild - amount >= 0:
		current_sheild -= amount
	else:
		current_hp -= amount
		if current_hp <= 0:
			game_over.emit(false)

func load_json_simple(file_path: String):
	var file = FileAccess.open(file_path, FileAccess.READ)
	if file:
		var json_string = file.get_as_text()
		file.close()
		
		# 直接解析，错误处理较少
		var data = JSON.parse_string(json_string)
		if data != null:
			return data
		else:
			push_error("JSON解析失败")
	return null

func auto_recover_shield():
	var current_time = Time.get_ticks_msec() / 1000.0
	# 检查是否距离上次受伤超过3秒且护盾未满
	if current_time - last_damage_time > SHIELD_RECOVERY_DELAY and current_sheild < max_sheild:
		# 缓慢恢复护盾
		current_sheild = min(current_sheild + SHIELD_RECOVERY_RATE * get_process_delta_time(), max_sheild)
